#! /usr/bin/env python
# -*- coding:utf-8 -*-

import requests
from lxml import etree
import datetime
import re
import uuid
import sys
import json
import logging
import demjson

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

resp = {
    'error' : 0,
    'msg' : 'success',
    'data' : {},
}

# 西安工程大学教务处IP
school_base_url = "http://202.200.206.54/"
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
}

# 拿Location字段，如果后期加入Cookie可避免Expection
session = requests.Session()

def getCourseInfo(req_data):
    # logger.info("The json params is: %s" % req_data)

    req_data = demjson.decode(req_data)
    location_word = req_data['location_url'].split('/')[1]

    data = {
        '__VIEWSTATE': 'dDw0NTM2NjI5MTg7Oz5khnyP8uikO2NTOQNIZOHZCUyxvA==',  # 固定
        'txtUserName': req_data['student_id'],  # 学号
        'Textbox1': '',
        'TextBox2': req_data['password'],  # 密码
        'txtSecretCode': req_data['code'],  # 验证码
        'RadioButtonList1': '(unable to decode value)',  # 固定
        'Button1': '',
        'lbLanguage': '',
        'hidPdrs': '',
        'hidsc': '',
    }
    # 登录必须带的头
    new_headers = {
        'Referer': 'http:/' + req_data['location_url'],
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    }
    # 必须请求登录一下，才能记录状体
    response = session.post(url=req_data['have_location_url'], headers=new_headers, data=data)
    if len(response.history) == 0:
        resp['msg'] = '登陆失败，请检查登陆信息'
        resp['error'] = '1'
        return resp

    # 学号
    student_id = req_data['student_id']
    school_year = req_data['school_year']
    term = req_data['term']
    html = etree.HTML(response.text)
    name = html.xpath('.//span[(@id="xhxm")]')[0].text
    id = int(student_id)
    # 请求课程表地址(固定)
    kb_url = 'http://202.200.206.54/' + location_word + '/tjkbcx.aspx?xh=' + str(id) + '&xm=%CE%E2%E9%AA&gnmkdm=N121601'
    # 请求课程表必须带的头
    headers = {
        'Referer': 'http://202.200.206.54/' + location_word + '/tjkbcx.aspx?xh=' + str(id) + '&xm=%CE%E2%E9%AA&gnmkdm=N121601',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    }

    courese_content = session.get(headers=headers, url=kb_url).text
    tree = etree.HTML(courese_content)

    # 学院
    xy = tree.xpath('//*[@id="xy"]/option[@selected="selected"]/@value')[0]
    # 班级
    kb = tree.xpath('//*[@id="kb"]/option[@selected="selected"]/@value')[0]
    # 年级
    nj = tree.xpath('//*[@id="nj"]/option[@selected="selected"]/@value')[0]
    # 学期
    xq = tree.xpath('//*[@id="xq"]/option[@selected="selected"]/@value')[0]
    # 学年
    xn = tree.xpath('//*[@id="xn"]/option[@selected="selected"]/@value')[0]

    data = {
        '__EVENTTARGET': 'kb',
        '__EVENTARGUMENT': '',
        '__VIEWSTATE': tree.xpath('.//input[@name="__VIEWSTATE"]/@value')[0],
        'xn': xn,  # 学年
        'xq': str(xq),  # 学期
        'nj': str(nj),  # 年级
        'xy': str(xy),  # 学院
        'zy': student_id[3:7],  # 专业
        'kb': kb,
    }

    if xn != (school_year + '-' + str(int(school_year)+1)):
        data['__EVENTTARGET'] = 'xn'
        data['__VIEWSTATE'] = tree.xpath('.//input[@name="__VIEWSTATE"]/@value')[0]
        data['xn'] = school_year + '-' + str(int(school_year)+1)
        courese_content = requests.post(url=kb_url, headers=headers, data=data).text
        tree = etree.HTML(courese_content)
        #logger.info("------ The request for xn ------")

    if term != xq:
        data['__EVENTTARGET'] = 'xq'
        data['__VIEWSTATE'] = tree.xpath('.//input[@name="__VIEWSTATE"]/@value')[0]
        data['xq'] = term
        courese_content = requests.post(url=kb_url, headers=headers, data=data).text
        tree = etree.HTML(courese_content)
        #logger.info("------ The request for xq ------")

    if nj != ('20' + student_id[1:3]):
        data['__EVENTTARGET'] = 'nj'
        data['__VIEWSTATE'] = tree.xpath('.//input[@name="__VIEWSTATE"]/@value')[0]
        data['nj'] = '20'+student_id[1:3]
        courese_content = requests.post(url=kb_url, headers=headers, data=data).text
        tree = etree.HTML(courese_content)
        #logger.info("------ The request for nj ------")

    temp_kb = tree.xpath('//*[@id="kb"]/option[@selected="selected"]/@value')[0]
    search_kb = '20' + student_id[1:3] + student_id[3:7] + school_year + '-' + str(int(school_year)+1) + term + student_id[3:7] + student_id[1:3] + '0' + str(int(student_id[7:9]))

    if search_kb != temp_kb:
        data['__EVENTTARGET'] = 'kb'
        data['__VIEWSTATE'] = tree.xpath('.//input[@name="__VIEWSTATE"]/@value')[0]
        data['kb'] = search_kb
        courese_content = requests.post(url=kb_url, headers=headers, data=data).text
        #logger.info("------ The request for kb ------")

    #logger.info("The data params is: %s" % data)

    return parseResponse(courese_content)


def parseResponse(courese_content):
    tree = etree.HTML(courese_content)
    # infos = tree.xpath('.//option[(@selected="selected")]')
    # infos.append(name)
    # noinspection PyBroadException
    table = tree.xpath('//*[@id="Table6"]/tr')
    try:
        week = table[0].xpath('./td[@align="Center"]//text()')
    except Exception as e:
        tree = etree.HTML(courese_content.text)
        error = tree.xpath('//*[@id="form1"]/script/text()')[0]
        # 匹配错误信息返回给前端
        rule = re.compile(r'[(](.*?)[)]', re.S)
        error_msg = re.findall(rule, error)
        return error_msg[0]
    new_table = []
    # 整个课表
    for index, value in enumerate(table):
        if index != 0 and (index % 2 == 0):
            new_table.append(value)
    # 最终课表信息
    course_info = []
    for index, br in enumerate(new_table):
        centers = br.xpath('./td[@align="Center"]')
        for index, center in enumerate(centers):
            try:
               str_list = center.xpath(".//text()")
            except BaseException:
                pass
            try:
                findall = str(re.findall(r"\d+,\d+", str_list[1])[0])
                split = findall.split(",")
                start_num = split[0]
                end_num = split[1]
            except BaseException:
                pass
            try:
                findall2 = str(re.findall(r"\d+,\d+", str_list[5])[0])
                findall__split = findall2.split(",")
                start1_num = findall__split[0]
                end1_num = findall__split[1]
            except BaseException:
                pass
            length = len(str_list)
            try:
                start = re.findall(r"\d+",str_list[1].split("(")[0].split("-")[0])[0]
            except BaseException:
                pass
            try:
                end = re.findall(r"\d+",str_list[1].split("(")[0].split("-")[1])[0]
            except BaseException:
                pass
            # 正常课表类型
            if length == 4 and (str_list[3] != ' '):
                course_weeks = [i for i in range(int(start),
                                                 int(end)+1)]
                info = {
                    "course_name": str_list[0],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[2],
                    "course_room": str_list[3],
                    "course_times": start_num + "-" + end_num,
                    "course_days": week[index],
                }
                course_info.append(info)
            elif length == 8 and (str_list[3] != ' '):
                start = re.findall(r"\d+", str_list[1].split("(")[0].split("-")[0])[0]
                try:
                    end = re.findall(r"\d+", str_list[1].split("(")[0].split("-")[1])[0]
                except Exception:
                    end = start
                start1 = re.findall(r"\d+", str_list[5].split("(")[0].split("-")[0])[0]
                try:
                    end1 = re.findall(r"\d+", str_list[5].split("(")[0].split("-")[1])[0]
                except Exception:
                    end1 = start1
                course_weeks = [i for i in range(int(start),
                                                 int(end)+ 1)]
                info = {
                    "course_name": str_list[0],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[2],
                    "course_room": str_list[3],
                    "course_times": start_num + "-" + end_num,
                    "course_days": week[index],
                }
                course_info.append(info)
                course_weeks = [i for i in range(int(start1),
                                                 int(end1)+ 1)]
                info = {
                    "course_name": str_list[4],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[6],
                    "course_room": str_list[7],
                    "course_times": start1_num + "-" + end1_num ,
                    "course_days": week[index],
                }
                course_info.append(info)
            # 没课
            elif length == 1:
                continue
            # 特殊课表类型
            elif length == 4:
                rule = re.compile(r'[(](.*?)[)]', re.S)
                course_weeks = [i for i in range(int(start),
                                                 int(end)+1)]
                info = {
                    "course_name": str_list[0],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[2],
                    "course_room": str_list[3],
                    "course_times": start_num + "-" + end_num,
                    "course_days": week[index],
                }
                course_info.append(info)
            elif length == 8:
                start = re.findall(r"\d+", str_list[1].split("(")[0].split("-")[0])[0]
                end = re.findall(r"\d+", str_list[1].split("(")[0].split("-")[1])[0]
                start1 = re.findall(r"\d+", str_list[5].split("(")[0].split("-")[0])[0]
                try:
                    end1 = re.findall(r"\d+", str_list[5].split("(")[0].split("-")[1])[0]
                except Exception:
                    end1 = start1
                course_weeks = [i for i in range(int(start), int(end)+1)]
                info = {
                    "course_name": str_list[0],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[2],
                    "course_room": str_list[3],
                    "course_times": start_num + "-" + end_num,
                    "course_days": week[index],
                }
                course_info.append(info)
                rule = re.compile(r'[(](.*?)[)]', re.S)
                course_weeks = [i for i in range(int(start1), int(end1)+1)]
                info = {
                    "course_name": str_list[4],
                    "course_weeks": course_weeks,
                    "course_teacher": str_list[6],
                    "course_room": str_list[7],
                    "course_times": start1_num + "-" + end1_num,
                    "course_days": week[index],
                }
                course_info.append(info)
    #course_info.append(infos)
    resp['data']['course_info'] = course_info
    return json.dumps(resp)


def main():
    req_data = sys.argv[1]
    resp = getCourseInfo(req_data)
    print(resp)
    #logger.info("The Course info is: %s" % resp)
    return resp

if __name__ == '__main__':
    main()


